package com.smedi.ismedi.file.core.infrastructure.listener;

import com.smedi.ismedi.cache.starter.util.RedisUtil;
import com.smedi.ismedi.file.core.application.service.FileApplicationService;
import com.smedi.ismedi.file.core.infrastructure.constant.ConstantField;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @Author: xulinjun
 * @Date: 2021-6-9 15:39
 */
@Slf4j
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private FileApplicationService fileApplicationService;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 捕捉符合的过期key，并调用业务逻辑
        String expressKey = new String(message.getBody(), StandardCharsets.UTF_8);
        if (expressKey.contains(ConstantField.profileTempPath)) {
            log.info("expressKey >>> {}", expressKey);
            String fileUUID = expressKey.replace(ConstantField.profileTempPath, "");
            log.info("fileUUID >>> {}", fileUUID);
            fileApplicationService.deleteFileBySignKey(fileUUID, "过期");
        }
    }
}
